package com.gs.synedocket.fragment;

import android.text.TextUtils;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gs.synedocket.R;
import com.gs.synedocket.adapter.TruckAdapter;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.bean.SyncBean;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.ShortDto;
import com.gs.synedocket.db.entity.UserTruck;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseFragment;
import com.gs.synedocket.presenter.TruckChangePresenter;
import com.gs.synedocket.util.AppUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.GsonUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.util.ToastUtil;
import com.gs.synedocket.view.ITruckChangeView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class TruckChangeFragment extends BaseFragment<ITruckChangeView, TruckChangePresenter> implements ITruckChangeView {

    private List<ShortDto> list;
    private TruckAdapter adapter;
    private int oldPos, newPos;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_truck_change;
    }

    @Override
    protected TruckChangePresenter createPresenter() {
        return new TruckChangePresenter();
    }

    @Override
    protected void initView() {
        RecyclerView recyclerView = fd(R.id.recyclerView);
        list = new ArrayList<>();
        adapter = new TruckAdapter(context, list, R.layout.rvitem_truck);
        adapter.setOnItemClickListener((v, position) -> {
            if (DocketUtil.getInstance().getUpgradeLevel() == AllConstants.UPGRADE_FIRST) {
                ToastUtil.showToast(R.string.upgrade_first);
                LogUtil.getInstance().insertOrReplaceData(getString(R.string.upgrade_log, AppUtil.getInstance().getVersion()));
                return;
            }
            try {
                newPos = position;
                mPresenter.changeTruck(list.get(position).getId(), list.get(position).getName());
                adapter.changeState(position);
            } catch (Exception ignored) {
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        mPresenter.combo("trucks&typeKeyId=" + SPUtil.getInstance().getString(AllConstants.ID));
    }

    @Override
    public void onGetComListSuccess(ApiResultData<List<ShortDto>> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            return;
        }
        if (apiResult.getData() == null) {
            return;
        }
        list.clear();
        list.addAll(apiResult.getData());
        adapter.notifyDataSetChanged();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getDef() != null && list.get(i).getDef()) {
                oldPos = i;
                break;
            }
        }
    }

    @Override
    public void onGetComListFails(Exception msg) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void onUploadSuccess(ApiResultData<String> apiResultData, String truckName, String truckId) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() != 2000) {
            adapter.changeState(oldPos);
            return;
        }
        UserTruck bean = new UserTruck();
        bean.setUserId(SPUtil.getInstance().getString(AllConstants.ID));
        bean.setTruckId(truckId);
        DBApi.getInstance().updateUserTruck(bean, list.get(oldPos).getId());
        changeQueryCache(truckName);
        LogUtil.getInstance().insertOrReplaceData("修改車牌號碼為" + truckName);
        SPUtil.getInstance().putString(AllConstants.TRUCK_NAME, truckName);
        EventBus.getDefault().post(new Event(EventCode.EVENT_TRUCK));
        oldPos = newPos;
    }

    private void changeQueryCache(String truckName) {
        changeQueryCache(AllConstants.ON_HAND_LIST, truckName);
        changeQueryCache(AllConstants.ON_HAND, truckName);
        changeQueryCache(AllConstants.LOG_LIST, truckName);
    }

    private void changeQueryCache(String mapKey, String truckName) {
        String logQuery = DBApi.getInstance().getQueryCacheMap(mapKey);
        if (TextUtils.isEmpty(logQuery)) {
            return;
        }
        SyncBean query = (SyncBean) GsonUtil.getInstance().fromJson(logQuery, SyncBean.class);
        query.setTruckNo(truckName);
        String json = GsonUtil.getInstance().toJson(query);
        DBApi.getInstance().setQueryCacheMap(mapKey, json);
    }

    @Override
    public void onUploadFail(Exception e) {
        adapter.changeState(oldPos);
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initData();
        }
    }
}
